/*
 * @Author: zengwj
 * @Date: 2022-08-08 18:01:16
 * @LastEditors: zengwj
 * @LastEditTime: 2022-08-09 16:22:22
 * @Description:
 */
// 数组原型对象
const arrayProto = Array.prototype
//创建新对象
const arrayMethods = Object.create(arrayProto)

// 要拦截的七个方法枚举
const methodsToPatch = [
	'push',
	'pop',
	'unshift',
	'shift',
	'splice',
	'sort',
	'reverse',
]

methodsToPatch.forEach((method) => {
	Object.defineProperty(arrayMethods, method, {
		value: function (...args) {
			const res = arrayProto[method].apply(this, args)
			console.log('处理响应式')
			let inserted = []
			switch (method) {
				case 'push':
				case 'unshift':
					inserted = args
					break
				case 'splice':
					inserted = args.slice(2)
					break
			}
			//如果数组有新增原生，则对新增元素响应式处理
			inserted.length && this.__ob__.observeArray(inserted)
			// 依赖更新
			this.__ob__.dep.notify()
			return res
		},
		configurable: true,
		writable: true,
		enumerable: true,
	})
})
export default function protoArgument(arr) {
	arr.__proto__ = arrayMethods
}
